<?php
namespace Common\Logic;

/**
 * 客人与会员相关信息
 * @modify zhangzhen 2017-02-14 创建
 */
class CustomerLogic extends \Common\Controller\BaseController {

    private $vipChannel = array(
        'zh_cn' => array(1=> '线下' ,2 => '线上'),
        'zh_tw' => array(1=> '線下' ,2 => '線上'),
        'en_us' => array(1=> 'Offline' ,2 => 'Online'),
    );

    /**
     * 获取客人信息 需要返回二维数组
     * @modify zhangzhen 2017-2-14    创建
     * @param  integer   $hotelId     客栈id
     * @param  integer   $mobile      预定人手机号
     * @param  integer   $pageIndex   分页页码
     * @param  integer   $pageSize    分页每页数量
     * @param  integer   $startDate    开始
     * @param  integer   $endDate    结束
     * @param  integer   $type    获取数据类型 1=筛选时的数据 2=获取导出表格时的数据
     * @return array                  客人信息
     */
    public function getCustomerInfos($hotelId, $keys = null, $pageIndex = null, $pageSize = null, $areaCode = null, $startDate = null, $endDate = null, $type = null) {

        if($pageIndex && $pageSize){
            $offset = ($pageIndex - 1) * $pageSize;
            $endOffset = $offset + $pageSize;
        }

        $orderInfoModel = D('OrderInfo');
        $orderInfos = $orderInfoModel->getInfoByHotelAndDate($hotelId, $startDate, $endDate);
        $orderInfoIdAll = array_column($orderInfos, 'id');
        $orderUserModel = D('OrderUser');
        $orderUserInfo = $orderUserModel->getInfoByOrder($orderInfoIdAll, $type);

        // 是否屏蔽身份证信息
        $adminAuthorityLogic = A('Common/AdminAuthority', 'Logic');
        $canSeeID = $adminAuthorityLogic->check($hotelId, null, AUTHORITY_ID_INFO_BLOCK);

        $adminHotelModel = D('AdminHotel');
        $userId = getUserId();
        $adminHotel = $adminHotelModel->getInfoByAdminHotel($userId, $hotelId);
        //不是客栈创建人员，需要检查操作权限
        $isAdmin = true;
        if ($adminHotel['role'] != HOTEL_ROLE_OWNER) {
            $isAdmin = false;
        }

        $orderRoomModel = D('OrderRoom');
        $userRoomModel = D('UserRoom');
        $longString = [
            'zh_cn' => ['晚','小时'],
            'zh_tw' => ['晚','小時'],
            'en_us' => ['nights','hour']
        ];

        foreach ($orderUserInfo as $key => &$orderUserItem) {
            $userRoomInfo = $userRoomModel->getInfosByOrderUser($orderUserItem['id']);
            // 获取房间状态（已入住，已退房） 
            $orderRoomInfo = $orderRoomModel->getInfo($userRoomInfo[0]['orderroom_id'], true, $startDate, $endDate);
            if (empty($orderRoomInfo)) {
                unset($orderUserInfo[$key]);
                continue;
            }

            // 筛选客人
            if (!is_null($keys)) {
                $searchString = $orderUserItem['mobile'] . $orderUserItem['name'];
                if (stripos($searchString, $keys) === false) {
                    unset($orderUserInfo[$key]);
                    continue;
                }
            }

            $orderUserItem['startDate'] = date('m/d H:i', strtotime($orderRoomInfo[0]['startdate']));
            // 入住日期 退房日期 入住房间 在导出表格使用 
            $orderUserItem['startTime'] = $orderRoomInfo[0]['startdate'];
            $orderUserItem['checkoutTime'] = $orderRoomInfo[0]['checkoutdate'];
            $orderUserItem['checkInRoomName'] = $orderRoomInfo[0]['roominfo_name'];

            if (isset($orderRoomInfo[0]['hour']) && $orderRoomInfo[0]['hour'] != 0) {
                // 钟点房
                $orderUserItem['hour'] = $orderRoomInfo[0]['hour'] . ' ' . $longString[LANG_SET][1];
            } elseif ($orderRoomInfo[0]['status'] == 2) {
                // 已入住
                $orderUserItem['night'] = $orderRoomInfo[0]['night'] . ' ' . $longString[LANG_SET][0];
            } elseif ($orderRoomInfo[0]['status'] == 3) {
                // 已退房
                $orderUserItem['night'] = $orderRoomInfo[0]['realnight'] . ' ' . $longString[LANG_SET][0];
            }

            $orderInfos = $orderInfoModel->getOrderCheckoutAndCheckIn($hotelId, $orderUserItem['mobile'], $orderUserItem['areacode']);
            $orderUserItem['receipt'] = !empty($orderInfos) && !is_null($orderInfos[0]['receipt']) ? $orderInfos[0]['receipt'] : '0.00';
            $orderUserItem['deposit'] = !empty($orderInfos) && !is_null($orderInfos[0]['deposit']) ? $orderInfos[0]['deposit'] : '0.00';
            // 统计入住次数
            $orderUserItem['checkin'] = $orderInfos[0]['checkin'];
            // 是否屏蔽身份证信息
            if ($canSeeID && !$isAdmin) {
                $orderUserItem['identity'] = !empty($orderUserItem['identity']) ? substr($orderUserItem['identity'], 0, 4) . '****' . substr($orderUserItem['identity'], mb_strlen($orderUserItem['identity'])-4) : $orderUserItem['identity'];
                $orderUserItem['idaddress'] = !empty($orderUserItem['idaddress']) ? mb_substr($orderUserItem['idaddress'], 0, 4) . '****' . mb_substr($orderUserItem['idaddress'], mb_strlen($orderUserItem['idaddress'])-4) : $orderUserItem['idaddress'];
            }

            $orderUserItem['orderUserId'] = $orderUserItem['id'];
            $orderUserItem['orderinfoId'] = $orderUserItem['orderinfo_id'];
            $orderUserItem['areaCode'] = $orderUserItem['areacode'];

            unset($orderUserItem['id']);
            unset($orderUserItem['orderinfo_id']);
            unset($orderUserItem['userlogin_id']);
            unset($orderUserItem['areacode']);
        }
        unset($orderUserItem);
        $orderUserInfo = array_values($orderUserInfo);

        // 分页
        $orderUserInfo = generatePageInfo($orderUserInfo, $pageIndex, $pageSize);

        $orderUserInfo['item'] = $orderUserInfo['hotelInfo'];
        $orderUserInfo['totaCustomer'] = $orderUserInfo['page']['total'];
        $orderUserInfo['page'] =  [
                'currentPage' => $orderUserInfo['page']['current'],
                'size' => $orderUserInfo['page']['size'],
                'total' => $orderUserInfo['page']['pageTotal'],
                'totalCount' => $orderUserInfo['page']['total'],
        ];
        unset($orderUserInfo['hotelInfo']);

        return $orderUserInfo;
    }
    /**
     * 获取会员信息 需要返回二维数组
     * @modify zhangzhen 2017-2-14    创建
     * @param  integer   $hotelId     客栈id
     * @param  integer   $mobile      预定人手机号
     * @param  integer   $pageIndex   分页页码
     * @param  integer   $pageSize    分页每页数量
     * @return array                  客人信息
     */
    public function getVipInfos($hotelId, $mobile = null, $vipInfoId = null, $allHotel = null, $pageIndex = null, $pageSize = null, $areaCode = null) {
        if($pageIndex && $pageSize){
            $offset = ($pageIndex - 1) * $pageSize;
            $endOffset = $offset + $pageSize;
        }
        $vipUserModel = D('VipUser');
        $vipUserCardModel = D('VipUserCard');
        $vipUserInfos = $vipUserModel->getVipsByHotel($hotelId, $mobile, $vipInfoId, $offset, $pageSize, $areaCode);
        if($allHotel == '1') {
            $adminHotelModel = D('AdminHotel');
            $hotelCreator = $adminHotelModel->getHotelCreator($hotelId);
            $adminHotelInfos = $adminHotelModel->getInfosByAdmin($hotelCreator['adminlogin_id']);
            //查询掌柜的酒店
            $hotelArray = array_column($adminHotelInfos, 'hotelentity_id');
            $hotelId = implode(',',$hotelArray);
        }
        $orderInfoModel = D('OrderInfo');
        foreach ($vipUserInfos as $key => &$vipUserInfo) {
            $orderInfos = $orderInfoModel->getCustomerByHotel($hotelId, $vipUserInfo['mobile'], null, null, $vipUserInfo['areacode']);
            if($orderInfos){
                $vipUserInfos[$key]['deposit'] = $orderInfos[0]['deposit'];
                $vipUserInfos[$key]['receipt'] = $orderInfos[0]['receipt'];
                $vipUserInfos[$key]['checkin'] = $orderInfos[0]['checkin'];
            }else{
                $vipUserInfos[$key]['deposit'] = '0.00';
                $vipUserInfos[$key]['receipt'] = '0.00';
                $vipUserInfos[$key]['checkin'] = '0';
            }
            $vipUserInfo['areaCode'] = $vipUserInfo['areacode'];
            unset($vipUserInfo['areacode']);

            $vipUserCardInfo = $vipUserCardModel->getInfoByVipUserId($vipUserInfo['id']);
            $vipUserInfo['cardPrice'] = isset($vipUserCardInfo['price']) ? $vipUserCardInfo['price'] : '0.00';
        }

        // 分页
        $vipUserInfos = generatePageInfo($vipUserInfos, $pageIndex, $pageSize);

        $vipUserInfos['item'] = $vipUserInfos['hotelInfo'];
        unset($vipUserInfos['hotelInfo']);

        if($pageIndex){
            $vipUserInfos['page'] =  [
                'currentPage' => $vipUserInfos['page']['current'],
                'size' => $vipUserInfos['page']['size'],
                'total' => $vipUserInfos['page']['pageTotal'],
                'totalCount' => $vipUserInfos['page']['total'],
            ];
        }

        return $vipUserInfos;
    }
    /**
     * 获取下单时会员信息 需要返回二维数组
     * @modify zhangzhen 2017-2-14    创建
     * @param  integer   $hotelId     客栈id
     * @param  integer   $vipUserId   会员ID
     * @param  integer   $vipInfoId   会员等级ID
     * @return array                  查询会员信息
     */
    public function getVipOrderInfo($hotelId, $vipUserId, $vipInfoId) {
        $vipUserModel = D('VipUser');
        $vipUserInfo = $vipUserModel->getInfoById($vipUserId);
        $vipInfoModel = D('VipInfo');
        $vipInfo = $vipInfoModel->getInfoById($vipInfoId);
        $orderInfoModel = D('OrderInfo');
        $orderInfos = $orderInfoModel->getCustomerByHotel($hotelId, $vipUserInfo['mobile'], null, null, $vipUserInfo['areacode']);
        if($orderInfos){
            $vipUserInfo['total'] = $orderInfos[0]['deposit']+$orderInfos[0]['receipt'];
            $vipUserInfo['average'] = round($vipUserInfo['total']/$orderInfos[0]['checkin'], 2);
            $vipUserInfo['checkin'] = $orderInfos[0]['checkin'];
            //最近入住的信息
            $orderRoomModel = D('OrderRoom');
            $recentOrder = $orderInfoModel->getOrderCheckout($hotelId, $vipUserInfo['mobile'], $vipUserInfo['areacode']);
            $orderRoomInfos = $orderRoomModel->getInfoByOrder($recentOrder['id'], false);
            $vipUserInfo['roomType'] = $orderRoomInfos[0]['roomtype_name'];
            $vipUserInfo['roomName'] = $orderRoomInfos[0]['roominfo_name'];

        }else{
            //处理数据，不能返回null，ios崩溃。
            $vipUserInfo['total'] = '0';
            $vipUserInfo['average'] = '0';
            $vipUserInfo['checkin'] = '0';
            $vipUserInfo['roomType'] = '';
            $vipUserInfo['roomName'] = '';
        }
        

        $returnData = [
            'levelName' => $vipInfo['name'],
            'name' => $vipUserInfo['name'],
            'mobile' => $vipUserInfo['mobile'],
            'identity' => $vipUserInfo['identity'],
            'checkin' => $vipUserInfo['checkin'],
            'total' => $vipUserInfo['total'],
            'average' => $vipUserInfo['average'],
            'roomType' => $vipUserInfo['roomType'],
            'roomName' => $vipUserInfo['roomName'],
        ];
        return $returnData;
    }
    /**
     * 获取会员信息 需要返回二维数组
     * @modify zhangzhen 2017-2-14    创建
     * @param  array   $param = [
     *                          'hotel' => ,
                                'name' => ,
                                'mobile' => ,
                                'areaCode' => ,
                                'vipInfoId' => ,
                                'identity' => ,
                                'gender' => ,
                                'birthday' => ,
                                'nation' => ,
                                'address' => ,
                                'wechat' => ,
                                'remark' => ,
                                'share' => ,
                                'vipLevelName' => ,
     *                       ]
     * @return array             成功ID
     */
    public function addVip($param) {
        $vipUserModel = D('VipUser');
        $existMobile = $vipUserModel->getInfoByMobile($param['hotel'], $param['mobile'], $param['areaCode']);
        if($existMobile){
            returnJson(403, 709);
        }
        $vipUserModel->startTrans();
        $vipInfoModel = D('VipInfo');
        //共享 要要多次添加
        if($param['share'] == '1'){
            $adminHotelModel = D('AdminHotel');
            $hotelCreator = $adminHotelModel->getHotelCreator($param['hotel']);
            $adminHotelInfos = $adminHotelModel->getInfosByAdmin($hotelCreator['adminlogin_id']);
            foreach ($adminHotelInfos as $adminHotelInfo) {
                $vipLevel = $vipInfoModel->getInfoByHotelName($adminHotelInfo['hotelentity_id'],$param['vipLevelName']);
                $addResult = $vipUserModel->addInfo($adminHotelInfo['hotelentity_id'], $vipLevel['id'], $param['name'], $param['mobile'], $param['identity'], $param['areaCode']);
                $vipUserId = $addResult;
                if($addResult){
                    $vipUserInfoModel = D('VipUserInfo');
                    $addResult = $vipUserInfoModel->addInfo($vipUserId,$param['gender'], $param['birthday'], $param['nation'], $param['address'], $param['wechat'], $param['remark']); 
                }
                if(empty($addResult)){
                    break;
                }
            }
        }else{
            $addResult = $vipUserModel->addInfo($param['hotel'], $param['vipInfoId'], $param['name'], $param['mobile'], $param['identity'], $param['areaCode']);
            $vipUserId = $addResult;
            if($addResult){
                $vipUserInfoModel = D('VipUserInfo');
                $addResult = $vipUserInfoModel->addInfo($vipUserId,$param['gender'], $param['birthday'], $param['nation'], $param['address'], $param['wechat'], $param['remark']); 
            }
        }

        if($addResult){
            $vipUserModel->commit();
            return true;
        }
        else{
            $vipUserModel->rollback();
            return false;
        }
    }
    /**
     * 查看会员详细信息
     * @modify zhangzhen 2017-02-15    创建
     * @param integer $hotelId        客栈ID
     * @param integer $vipUserId      会员ID
     * @return type
     */
    public function setVip($hotelId, $vipUserId) {
        $vipUserModel = D('VipUser');
        $vipUserInfo = $vipUserModel->getLeftJoinInfoById($vipUserId);
        $orderInfoModel = D('OrderInfo');
        $orderInfos = $orderInfoModel->getInfosByMobile($hotelId, $vipUserInfo['mobile'], $vipUserInfo['areacode']);
        if($orderInfos){
            $orderRoomModel = D('OrderRoom');
            foreach ($orderInfos as $info => &$orderInfo) {
                $orderInfos[$info]['date'] = substr($orderInfo['createtime'], 0, 10);
                $orderInfos[$info]['time'] = substr($orderInfo['createtime'], 11);
                unset($orderInfos[$info]['createtime']);
                $orderRoomInfos = $orderRoomModel->getInfoByOrder($orderInfo['id'], false);
                foreach ($orderRoomInfos as $room => $orderRoomInfo) {
                    $orderInfos[$info]['room'] .= $orderRoomInfo['roomtype_name'].'-'.$orderRoomInfo['roominfo_name'].' ';
                }
                // 选择语言
                switch (LANG_SET) {
                    case 'zh_cn':
                        $orderInfo['name'] = explode('/', $orderInfo['name'])[0];
                        break;
                    case 'en_us':
                        $orderInfo['name'] = explode('/', $orderInfo['name'])[1];
                        break;
                    case 'zh_tw':
                        $orderInfo['name'] = explode('/', $orderInfo['name'])[2];
                        break;
                    default:
                        $orderInfo['name'] = explode('/', $orderInfo['name'])[0];
                        break;
                }
            }

        }

        $vipUserInfo['areaCode'] = $vipUserInfo['areacode'];
        unset($vipUserInfo['areacode']);

        $vipUserInfo['detail'] = $orderInfos;
        return $vipUserInfo;
    }
    /**
     * 添加会员等级
     * @modify zhangzhen 2017-2-18    创建
     * @param  array   $param = [
     *                          'hotel' => ,
                                'name' => ,
                                'mobile' => ,
                                'vipInfoId' => ,
                                'identity' => ,
                                'gender' => ,
                                'birthday' => ,
                                'nation' => ,
                                'address' => ,
                                'wechat' => ,
                                'remark' => ,
                                'share' => ,
                                'vipLevelName' => ,
                                'vipUserId' => ,
     *                       ]
     * @return array             成功ID
     */
    public function editVip($param) {
        $vipUserModel = D('VipUser');
        //检查号码是否存在
        $existMobile = $vipUserModel->getInfoByMobile($param['hotel'], $param['mobile'], $param['areaCode']);
        if(!empty($existMobile) && $existMobile['id'] != $param['vipUserId']){
            returnJson(403, 709);
        }
        $vipUserInfo = $vipUserModel->getInfoById($param['vipUserId']);
        $vipUserInfoModel = D('VipUserInfo');
        //不需要修改会员等级
        if($vipUserInfo['vipinfo_id'] == $param['vipInfoId']){
            if($param['share'] == '1'){
                $adminHotelModel = D('AdminHotel');
                $hotelCreator = $adminHotelModel->getHotelCreator($param['hotel']);
                $adminHotelInfos = $adminHotelModel->getInfosByAdmin($hotelCreator['adminlogin_id']);
                //获取掌柜下的酒店ID
                $hotelIds = implode(',',array_column($adminHotelInfos, 'hotelentity_id'));

                $vipUserInfos = $vipUserModel->getInfosByMobile($hotelIds, $vipUserInfo['mobile'], $vipUserInfo['areacode']);
                //需要编辑的Id
                $vipUserIds = implode(',',array_column($vipUserInfos, 'id'));
                //修改tb_vip_user
                $result = $vipUserModel->saveInfo($vipUserIds, null, $param['name'], $param['mobile'], $param['identity'], $param['areaCode']);
                //修改tb_vip_user_info
                if($result){
                    $result = $vipUserInfoModel->saveInfo($vipUserIds,$param['gender'], $param['birthday'], $param['nation'], $param['address'], $param['wechat'], $param['remark']);
                }
                
                return $result;
            }else{
                $result = $vipUserModel->saveInfo($param['vipUserId'], null, $param['name'], $param['mobile'], $param['identity'], $param['areaCode']);
                if($result){
                    $result = $vipUserInfoModel->saveInfo($param['vipUserId'],$param['gender'], $param['birthday'], $param['nation'], $param['address'], $param['wechat'], $param['remark']);
                }

                return $result;
            }
           

        //需要修改会员等级
        }else{
            if($param['share'] == '1'){
                $vipUserModel->startTrans();
                $vipInfoModel = D('VipInfo');
                $adminHotelModel = D('AdminHotel');
                $hotelCreator = $adminHotelModel->getHotelCreator($param['hotel']);
                $adminHotelInfos = $adminHotelModel->getInfosByAdmin($hotelCreator['adminlogin_id']);
                //修改会员等级需要循环找出会员等级Id再添加
                foreach ($adminHotelInfos as $adminHotelInfo) {
                    $vipLevel = $vipInfoModel->getInfoByHotelName($adminHotelInfo['hotelentity_id'],$param['vipLevelName']);
                    $vipUser = $vipUserModel->getInfoByMobile($adminHotelInfo['hotelentity_id'], $vipUserInfo['mobile'], $vipUserInfo['areacode']);
                    $result = $vipUserModel->saveInfo($vipUser['id'], $vipLevel['id'], $param['name'], $param['mobile'], $param['identity'], $param['areaCode']);
                    if($result){
                        $result = $vipUserInfoModel->saveInfo($vipUser['id'],$param['gender'], $param['birthday'], $param['nation'], $param['address'], $param['wechat'], $param['remark']); 
                    }
                    if(empty($result)){
                        break;
                    }
                }
                if($result){
                    $vipUserModel->commit();
                    return true;
                }
                else{
                    $vipUserModel->rollback();
                    return false;
                }
            } else {
                $result = $vipUserModel->saveInfo($param['vipUserId'], $param['vipInfoId'], $param['name'], $param['mobile'], $param['identity'], $param['areaCode']);
                if($result){
                    $result = $vipUserInfoModel->saveInfo($param['vipUserId'],$param['gender'], $param['birthday'], $param['nation'], $param['address'], $param['wechat'], $param['remark']); 
                }
                return $result;
            }
        }
        
    }
    /**
     * 添加会员等级
     * @modify zhangzhen 2017-02-15    创建
     * @param integer $name           等级名称
     * @param integer $hotelId        客栈ID
     * @param string  $auto           自动升级
     * @param string  $level          升级
     * @param string  $levelRule      升级方式
     * @param string  $discount       打折
     * @param string  $discountRule   打折方式
     * @return type
     */
    public function addVipLevel($name, $hotelId, $auto, $level, $levelRule, $discount, $discountRule, $share) {
        $vipInfoModel = D('VipInfo');
        $vipNameInfos = $vipInfoModel->getInfoByHotel($hotelId);
        foreach ($vipNameInfos as $key => $vipNameInfo) {
            if($vipNameInfo['name'] == $name){
                returnJson(403, 707);
            }
            if($vipNameInfo['auto']=='1' && ($vipNameInfo['levelrule'] == $levelRule)){
                returnJson(403, 708);
            }
        }
        if($share == '1'){
            $adminHotelModel = D('AdminHotel');
            $hotelCreator = $adminHotelModel->getHotelCreator($hotelId);
            $adminHotelInfos = $adminHotelModel->getInfosByAdmin($hotelCreator['adminlogin_id']);
            foreach ($adminHotelInfos as $adminHotelInfo) {
                $vipLevelInfo = $vipInfoModel->addInfo($name, $adminHotelInfo['hotelentity_id'], $auto, $level, $levelRule, $discount, $discountRule); 
                if($adminHotelInfo['hotelentity_id'] == $hotelId){
                    $result = $vipLevelInfo;
                }
            }
        }else{
            $result = $vipInfoModel->addInfo($name, $hotelId, $auto, $level, $levelRule, $discount, $discountRule); 
        }
        return $result;
    }
    /**
     * 更新用户数据
     * @modify zhangzhen 2017-02-16
     * @param integer $id             id
     * @param integer $name           等级名称
     * @param integer $hotelId        客栈ID
     * @param string  $auto           自动升级
     * @param string  $level          升级
     * @param string  $levelRule      升级方式
     * @param string  $discount       打折
     * @param string  $discountRule   打折方式
     * @return type
     */
    public function editVipLevel($id, $name, $hotelId, $auto, $level, $levelRule, $discount, $discountRule, $share) {
        $vipInfoModel = D('VipInfo');
        $vipNameInfos = $vipInfoModel->getInfoByHotel($hotelId);

        foreach ($vipNameInfos as $key => $vipNameInfo) {
            if($vipNameInfo['id'] == $id){
                $vipName = $vipNameInfo['name'];
                continue;
            }
            if($vipNameInfo['name'] == $name){
                returnJson(403, 707);
            }
            if($vipNameInfo['auto']=='1' && ($vipNameInfo['levelrule'] == $levelRule)){
                returnJson(403, 708);
            }
        }
        if($share == '1'){
            $adminHotelModel = D('AdminHotel');
            $hotelCreator = $adminHotelModel->getHotelCreator($hotelId);
            $adminHotelInfos = $adminHotelModel->getInfosByAdmin($hotelCreator['adminlogin_id']);
            foreach ($adminHotelInfos as $adminHotelInfo) {
                $vipInfoId = $vipInfoModel->getInfoByHotelName($adminHotelInfo['hotelentity_id'],$vipName);
                $vipLevelInfo = $vipInfoModel->saveInfo($vipInfoId['id'], $name, $auto, $level, $levelRule, $discount, $discountRule); 
            }
        }else{
            $vipLevelInfo = $vipInfoModel->saveInfo($id, $name, $auto, $level, $levelRule, $discount, $discountRule); 
        }
        return $vipLevelInfo;
    }

    /**
     * 添加会员卡
     * @modify wenhui 2017-12-06    创建
     * @param int  $hotelId           客栈id
     * @param int  $vipUserId           会员id
     * @param decimod  $cardPrice        金额 有正负
     * @param int  $payType        支付类型
     * @param string  $remark      备注
     * @param int  $type      1=充值 2=消费 3=退款
     * @param int  $channel      操作端 0=美住网页 1=支美住app 2=微预定
     */
    public function setVipUserCard ($hotelId, $vipUserId, $cardPrice, $payType, $remark, $type = 1, $channel = 0) {
        $adminHotelModel = D('AdminHotel');
        $adminLoginModel = D('AdminLogin');
        $vipUserModel = D('VipUser');
        $vipUserCardModel = D('VipUserCard');
        $vipUserCardRecordModel = D('VipUserCardRecord');
        $vipInitModel = D('VipInit');

        // 是否会员
        $existMobile = $vipUserModel->getInfoById($vipUserId);
        if(empty($existMobile)){
            returnJson(403, 709);
            return false;
        }

        $vipUserCardModel->startTrans();
        $commit = true;

        $hotelCreator = $adminHotelModel->getHotelCreator($hotelId);
        // 会员分享方式
        $vipInitInfo = $vipInitModel->getInfoByAdmin($hotelCreator['adminlogin_id']);
        if (empty($vipInitModel)) {
            $commit = false;
            returnJson(403, 709);
            return false;
        }

        // 记录数据
        $addRecordData = array();
        $adminId = getUserId();
        // 是否存在会员卡
        $vipUserCardInfo = $vipUserCardModel->getInfoByVipUserId($vipUserId);

        if (!empty($vipUserCardInfo)) {
            $price = $cardPrice + $vipUserCardInfo['price'];
            // 卡余额小于 999999.99
            if ($price > 999999.99) {
                $commit = false;
                returnJson(403, 712);
                return false;
            }

            if($vipInitInfo['share'] == '1'){
                $adminHotelInfos = $adminHotelModel->getInfosByAdmin($hotelCreator['adminlogin_id']);
                $hotelIds = array_column($adminHotelInfos, 'hotelentity_id');
                $vipUserInfo = $vipUserModel->getInfosByMobile($hotelIds, $existMobile['mobile'], $existMobile['areacode']);

                // 获取支付方式
                $hotelLogic = A('Common/Hotel', 'Logic');
                $hotelpayInfo = $hotelLogic->getHotelPay($hotelIds, true, 'zh_cn', true);
                $hotelpayInfo = getArrayValueAsIndex($hotelpayInfo, 'hotelentity_id');
                foreach ($hotelpayInfo as $key => &$hotelpayItem) {
                    $hotelpayItem = getArrayValueAsIndex($hotelpayItem, 'id');
                }
                unset($hotelpayItem);

                foreach ($vipUserInfo as $key => $vipUserItem) {
                    $saveResult = $vipUserCardModel->saveVipUserCardInfo($vipUserItem['id'], $price);
                    if ($saveResult === false) {
                        $commit = false;
                        break;
                    }

                    // 获取支付方式id
                    foreach ($hotelpayInfo[$vipUserItem['hotelentity_id']] as $key => $hotelpayItem) {
                        if ($hotelpayInfo[$hotelId][$payType]['name'] == $hotelpayItem['name']) {
                            $hotelPayType = $hotelpayItem['id'];
                        }
                    }
                    unset($hotelpayItem);

                    // 记录数据
                    array_push($addRecordData, array(
                        'hotelentity_id' => $hotelId, // 当前操作客栈
                        'vipuser_id' => $vipUserItem['id'],
                        'price' => $price,
                        'change_price' => $cardPrice,
                        'type' => $type,
                        'channel' => $channel,
                        'pay_type' => isset($hotelPayType) ? $hotelPayType : '0',
                        'remark' => $remark,
                        'creator' => $adminId,
                        'operator' => $adminId,
                    ));
                }
                unset($vipUserItem);
            } else {
                $saveResult = $vipUserCardModel->saveVipUserCardInfo($vipUserId, $price);
                if ($saveResult === false) {
                    $commit = false;
                }
                // 记录数据
                array_push($addRecordData, array(
                    'hotelentity_id' => $hotelId, // 当前操作客栈
                    'vipuser_id' => $vipUserId,
                    'price' => $price,
                    'change_price' => $cardPrice,
                    'type' => $type,
                    'channel' => $channel,
                    'pay_type' => $payType,
                    'remark' => $remark,
                    'creator' => $adminId,
                    'operator' => $adminId,
                ));
            }
        } else {
            $price = $cardPrice;
            if($vipInitInfo['share'] == '1'){

                $adminHotelInfos = $adminHotelModel->getInfosByAdmin($hotelCreator['adminlogin_id']);
                $hotelIds = array_column($adminHotelInfos, 'hotelentity_id');
                $vipUserInfo = $vipUserModel->getInfosByMobile($hotelIds, $existMobile['mobile'], $existMobile['areacode']);

                // 获取支付方式id
                $hotelLogic = A('Common/Hotel', 'Logic');
                $hotelpayInfo = $hotelLogic->getHotelPay($hotelIds, true, 'zh_cn', true);
                $hotelpayInfo = getArrayValueAsIndex($hotelpayInfo, 'hotelentity_id');
                foreach ($hotelpayInfo as $key => &$hotelpayItem) {
                    $hotelpayItem = getArrayValueAsIndex($hotelpayItem, 'id');
                }
                unset($hotelpayItem);

                foreach ($vipUserInfo as $key => $vipUserItem) {
                    $vipUserCardInfo = $vipUserCardModel->getInfoByVipUserId($vipUserItem['id']);
                    if (!empty($vipUserCardInfo)) {
                        $newPrice =  $cardPrice + $vipUserCardInfo['price'];
                        $addResult = $vipUserCardModel->saveVipUserCardInfo($vipUserItem['id'], $newPrice);
                    } else {
                        $addResult = $vipUserCardModel->addVipUserCardInfo($vipUserItem['hotelentity_id'], $vipUserItem['id'], $price);
                    }
                    if ($addResult == false) {
                        $commit = false;
                        break;
                    }

                    foreach ($hotelpayInfo[$vipUserItem['hotelentity_id']] as $key => $hotelpayItem) {
                        if ($hotelpayInfo[$hotelId][$payType]['name'] == $hotelpayItem['name']) {
                            $hotelPayType = $hotelpayItem['id'];
                        }
                    }
                    unset($hotelpayItem);

                    // 记录数据
                    array_push($addRecordData, array(
                        'hotelentity_id' => $hotelId, // 当前操作客栈
                        'vipuser_id' => $vipUserItem['id'],
                        'price' => $price,
                        'change_price' => $cardPrice,
                        'type' => $type,
                        'channel' => $channel,
                        'pay_type' => isset($hotelPayType) ? $hotelPayType : '0',
                        'remark' => $remark,
                        'creator' => $adminId,
                        'operator' => $adminId,
                    ));
                }
                unset($vipUserItem);
            } else {
                $addResult = $vipUserCardModel->addVipUserCardInfo($hotelId, $vipUserId, $price);
                if ($addResult == false) {
                    $commit = false;
                }
                // 记录数据
                array_push($addRecordData, array(
                    'hotelentity_id' => $hotelId, // 当前操作客栈
                    'vipuser_id' => $vipUserId,
                    'price' => $price,
                    'change_price' => $cardPrice,
                    'type' => $type,
                    'channel' => $channel,
                    'pay_type' => $payType,
                    'remark' => $remark,
                    'creator' => $adminId,
                    'operator' => $adminId,
                ));
            }
        }


        if ($commit && !empty($addRecordData)) {
            // 添加记录
            $addResult = $vipUserCardRecordModel->addAll($addRecordData);
            if ($addResult == false) {
                $commit = false;
            }
        }

        // 获取支付方式信息用作补充
        $hotelLogic = A('Common/Hotel', 'Logic');
        $payResource = $hotelLogic->getHotelPay($hotelId);
        $payResource = getArrayValueAsIndex($payResource, 'id');
        // 操作人
        $adminLoginInfo = $adminLoginModel->getInfo($adminId);

        $returnData = array(
            'price' => $price,
            'changePrice' => $cardPrice,
            'type' => $type,
            'payType' => $payResource[$payType]['name'],
            'remark' => $remark,
            'createDate' => date('Y-m-d H:i:s'),
            'operator' => $adminLoginInfo['name'],
        );

        if ($commit) {
            $vipUserCardModel->commit();
            return $returnData;
        } else {
            $vipUserCardModel->rollback();
            returnJson(500, 506);
            return false;
        }
    }

    /**
     * 添加会员卡
     * @modify wenhui 2017-12-06    创建
     * @param int  $hotelId           客栈id
     * @param int  $vipUserId           会员id
     */
    public function getVipCardRecord ($hotelId, $vipUserId, $langSet = null) {
        $vipUserCardModel = D('VipUserCard');
        $vipUserCardRecordModel = D('VipUserCardRecord');
        $adminLoginModel = D('AdminLogin');
        $userLoginModel = D('UserLogin');

        $vipUserCardInfo = $vipUserCardModel->getInfoByVipUserId($vipUserId);
        $recordInfo = $vipUserCardRecordModel->getVipCardRecord($vipUserId);
        $langSet = !is_null($langSet) ? $langSet : LANG_SET;
        // 处理数据
        if (!empty($recordInfo)) {
            // 获取支付方式信息用作补充
            $hotelLogic = A('Common/Hotel', 'Logic');
            $payResource = $hotelLogic->getHotelPay($hotelId, true, $langSet, true);
            $payResource = getArrayValueAsIndex($payResource, 'id');

            foreach ($recordInfo as $key => &$recordItem) {
                if ($recordItem['operator'] != 0) {
                    $adminInfo = $adminLoginModel->getInfo($recordItem['operator']);
                    $name = $adminInfo['name'];
                } else {
                    $userInfo = $userLoginModel->getInfo($recordItem['bk_user_id']);
                    $name = $userInfo['name'];
                }

                $channel = $recordItem['channel'] == ORDER_CHANGE_BOOK_WEB ? $this->vipChannel[$langSet][2] : $this->vipChannel[$langSet][1];
                $recordItem['channel'] = $channel;
                $recordItem['operator'] = $name;
                $recordItem['changePrice'] = $recordItem['change_price'];
                $recordItem['payType'] = $payResource[$recordItem['pay_type']]['name'];
                $recordItem['createDate'] = $recordItem['createtime'];
                unset($recordItem['change_price']);
                unset($recordItem['pay_type']);
                unset($recordItem['createtime']);
                unset($recordItem['id']);
                unset($recordItem['vipuser_id']);
                unset($recordItem['bk_user_id']);
            }
            unset($recordItem);
        }

        $returnData['recordInfo'] = $recordInfo;
        $returnData['price'] = isset($vipUserCardInfo['price']) ? $vipUserCardInfo['price'] : '0.00';

        return $returnData;
    }

    /**
     * 会员卡退款
     * @modify wenhui 2018-01-16    创建
     * @param string  $hotelId           客栈id
     * @param string  $mobile           手机号
     * @param string  $areaCode           区号
     * @param int  $orderId           订单id
     * @param int  $hotelPayId           客栈支付方式
     * @param decimal  $price           退款金额
     */
    public function refundVipCardInfo ($hotelId, $mobile, $areaCode, $orderId, $hotelPayId, $price) {
        $vipUserModel = D('VipUser');
        $orderPayRecordModel = D('OrderPayRecord');
        $orderPayRecordInfo = $orderPayRecordModel->getInfoByOrderIdAnPayId($orderId, $hotelPayId);
        // 是否有会员卡收款记录
        if (empty($orderPayRecordInfo)) {
            return true;
        }

        $vipUserInfo = $vipUserModel->getInfoByMobile($hotelId, $mobile, $areaCode);
        // 执行退款
        $returnData = $this->setVipUserCard($hotelId, $vipUserInfo['id'], $price, $hotelPayId, '', 3);
        if (!empty($returnData)) {
            return true;
        }

        return false;
    }
}
